﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GPSTrackingWebsiteManager
{
    public partial class ForgotPassword : Telerik.Web.UI.RadAjaxPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void btnSendPassword_Click(object sender, EventArgs e)
        {
            try
            {
               
                if (RadCaptcha1.IsValid)
                {

                    if (!string.IsNullOrEmpty(Request.Params["loginpwd"]))
                    {
                        string loginpwd = Request.QueryString["loginpwd"];
                        string email = string.Empty;
                        string name = string.Empty;
                        string newPass = string.Empty;

                        if (loginpwd == "master")
                        {
                            GPSTrackingDBV2.Data.MastersQuery mastersQuery = new GPSTrackingDBV2.Data.MastersQuery();
                            mastersQuery.AppendEquals(GPSTrackingDBV2.Entities.MastersColumn.Email, txtEmail.Text);

                            GPSTrackingDBV2.Entities.Masters masterEntity = GPSTrackingDBV2.Data.DataRepository.MastersProvider.Find(mastersQuery).FirstOrDefault();
                            if (masterEntity != null)
                            {
                                email = masterEntity.Email;
                                name = masterEntity.Name;
                                newPass = masterEntity.Name.Substring(0, 1) +
                                          masterEntity.FirstName.Substring(0, 1) +
                                          masterEntity.LastName.Substring(0, 1) +
                                          DateTime.Now.Ticks.ToString().Substring(DateTime.Now.Ticks.ToString().Length - 5, 5);                                          

                                string newPassEncrypt = EncryptaionManager.EncryptionManager.Encrypt(newPass, new System.Security.Cryptography.SHA256CryptoServiceProvider());

                                masterEntity.Password = newPassEncrypt;

                                GPSTrackingDBV2.Data.DataRepository.MastersProvider.Update(masterEntity);
                            }
                            else
                            {
                                ShowErrorMessage("El correo digitado no existe");
                            }
                        }

                        if (loginpwd == "admin")
                        {
                            GPSTrackingDBV2.Data.AdministratorsQuery administratorsQuery = new GPSTrackingDBV2.Data.AdministratorsQuery();
                            administratorsQuery.AppendEquals(GPSTrackingDBV2.Entities.AdministratorsColumn.Email, txtEmail.Text);

                            GPSTrackingDBV2.Entities.Administrators adminEntity = GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.Find(administratorsQuery).FirstOrDefault();
                            if (adminEntity != null)
                            {
                                email = adminEntity.Email;
                                name = adminEntity.Name;
                                newPass = adminEntity.Name.Substring(0, 1) +
                                          adminEntity.FirstName.Substring(0, 1) +
                                          adminEntity.LastName.Substring(0, 1) +
                                          DateTime.Now.Ticks.ToString().Substring(DateTime.Now.ToString().Length - 5, 5);   

                                string newPassEncrypt = EncryptaionManager.EncryptionManager.Encrypt(newPass, new System.Security.Cryptography.SHA256CryptoServiceProvider());                                

                                adminEntity.Password = newPassEncrypt;

                                GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.Update(adminEntity);
                            }
                            else
                            {
                                ShowErrorMessage("El correo digitado no existe");
                            }
                        }

                        if (loginpwd == "user")
                        {
                            GPSTrackingDBV2.Data.UsersQuery userQuery = new GPSTrackingDBV2.Data.UsersQuery();
                            userQuery.AppendEquals(GPSTrackingDBV2.Entities.UsersColumn.Email, txtEmail.Text);

                            GPSTrackingDBV2.Entities.Users userEntity = GPSTrackingDBV2.Data.DataRepository.UsersProvider.Find(userQuery).FirstOrDefault();
                            if (userEntity != null)
                            {
                                email = userEntity.Email;
                                name = userEntity.Name;
                                newPass = userEntity.Name.Substring(0, 1) +
                                          userEntity.FirstName.Substring(0, 1) +
                                          userEntity.LastName.Substring(0, 1) +
                                          DateTime.Now.Ticks.ToString().Substring(DateTime.Now.Ticks.ToString().Length - 5, 5);   

                                string newPassEncrypt = EncryptaionManager.EncryptionManager.Encrypt(newPass, new System.Security.Cryptography.SHA256CryptoServiceProvider());

                                userEntity.Password = newPassEncrypt;

                                GPSTrackingDBV2.Data.DataRepository.UsersProvider.Update(userEntity);

                            }
                            else
                            {
                                ShowErrorMessage("El correo digitado no existe");
                            }
                        }



                        if (!string.IsNullOrEmpty(email))
                        {
                            string html = System.IO.File.ReadAllText(Server.MapPath("Template/Html/ForgotPassword.html"));

                            string ApplicationName = System.Configuration.ConfigurationManager.AppSettings["ApplicationName"];
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            sb.AppendLine("Saludos," + name);
                            sb.AppendLine("<BR />");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("De parte de " + ApplicationName + " te enviamos tu nueva contraseña: " + newPass);
                            sb.AppendLine("<BR />");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("* Recuerda cambiar tu contraseña con regularidad *");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("Atentamente,");
                            sb.AppendLine("Falcon System Soporte");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("<BR />");
                            sb.AppendLine("Nota: Este correo es solo para entregas de contraseñas si respondes este correo no será visto por ninguno de nuestro personal");

                            html = html.Replace("{Text}", sb.ToString());
                            html = html.Replace("{Year}", DateTime.Now.Year.ToString());

                            EmailManager.EmailManager.Send(email, "Nueva contraseña " + ApplicationName, html, true);

                            ShowMessage("Tu nueva contraseña fue enviada a tu correo: " + email.Split(new char[] { '@' })[1]);
                        }


                    }
                    else
                        ShowErrorMessage("Parametros de login no existe");
                }
                else
                    ShowErrorMessage("Captcha no es correcto");
            }
            catch(Exception ex)
            {
                    ShowErrorMessage("Error - " + ex.Message);
            }

        }

        public void ShowErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Recuperación de contraseña');", true);
        }

        public void ShowMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Info", "objWindowsMessageManager.show_Info('" + msg + "','Recuperación de contraseña');", true);
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            if (Request.Cookies["GUID"] != null)
                Response.Redirect(Request.Cookies["Login"].Value + ".aspx?Guid=" + Request.Cookies["GUID"].Value, true);
            else
                Response.Redirect(Request.Cookies["Login"].Value + ".aspx", true);
        }
    }
}